package com.example.practical_training_projects.controller;

import com.example.practical_training_projects.entity.pc;
import com.example.practical_training_projects.entity.user;
import com.example.practical_training_projects.service.pcService;
import com.example.practical_training_projects.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("pc")
@CrossOrigin
public class pcController {

    /**
     * 返回所有电脑信息：http://localhost:8080/pc/list get请求
     * 添加电脑信息：http://localhost:8080/pc/add post请求
     * 删除电脑信息 http://localhost:8080/pc/del/{{pc_uid}} get请求
     * 修改电脑信息 http://localhost:8080/pc/update post请求
     * 通过电脑名称查询电脑信息 http://localhost:8080/pc/query/{{pc_name}} get请求
     */

    private final pcService service;

    @Autowired
    public pcController(pcService service) {
        this.service = service;
    }

    @GetMapping("list")
    public List<pc> getAllpc() {
        return service.getAllpc();
    }
    //分页
    @GetMapping("/page")
    public PageInfo<pc> getAllpcpage(Integer pageNum, Integer pageSize){
        PageInfo<pc> pageInfo = service.findpcpage(pageNum,pageSize);
        return pageInfo;
    }

    @PostMapping("add")
    public Integer insertPc(@RequestBody pc pc) {
        return service.insertPc(pc);
    }

    @GetMapping("/del/{pc_uid}")
    public Integer deletePc(@PathVariable("pc_uid") Integer pc_uid) {
        return service.deletePc(pc_uid);
    }

    @PostMapping("update")
    public Integer updatePc(@RequestBody pc pc) {
        return service.updatePc(pc);
    }

    @GetMapping("/query/{pc_name}")
    public List<pc> getpcBYName(@PathVariable("pc_name") String pc_name) {
        return service.getpcBYName(pc_name);
    }

    @GetMapping("/get/{pc_uid}")
    public pc findPcid(@PathVariable("pc_uid") Integer pc_uid) {
        return service.findPcid(pc_uid);
    }

    @PostMapping ("/upload")
    public String getPicFileName(MultipartFile file){
        String oldFileName = file.getOriginalFilename();
        System.out.println(oldFileName);
        String typeName = oldFileName.substring(oldFileName.lastIndexOf('.'));
        String filePath = FileUtil.getUpLoadFilePath();
        System.out.println(typeName);
        String newFileName = System.currentTimeMillis()+typeName;

        try {
            FileUtil.uploadFile(file.getBytes(),filePath,newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }

}